﻿//type: 0 search place; 1: search start point for route; 2: search end point for route
function gplaceSearch(address, cityId, type) {

    $.ajax({
        url: "city/" + cityId,
        async: false,
        dataType: 'json',
        success: function (item) {
            var north_east = new google.maps.LatLng(item.north_east_lat, item.north_east_lng);
            var south_west = new google.maps.LatLng(item.south_west_lat, item.south_west_lng);

            var bound = new google.maps.LatLngBounds(south_west, north_east);
            var request = {
                bounds: bound,
                keyword: address
            };

            var service = new google.maps.places.PlacesService(map);
            switch (type) {
                case '0': service.search(request, gplaceSearch_callback);
                    break;
                case '1': service.search(request, gStartPointSearch_callback);
                    break;
                case '2': service.search(request, gEndPointSearch_callback); ;
                    break;
            } 
        }
    });
}

//search place
function gplaceSearch_callback(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
        var line;
        $("#sumResult").html("(" + results.length + ")"); //show sum of search result
        for (var i = 0; i < results.length; i++) {
            var item = results[i];
            if (isGPlace(item.types)) {
                line = '<li>'
                                + '<a onclick="moveToGPlace(' + "'" + item.reference + "'" + ')">' + item.name + '</a><br />'
                                + '<span>' + item.vicinity + '</span>'
                                + '<br/><span id="action"><a onclick="updateStartPoint(' + "'" + item.reference + "'" + ',' + "'" + item.name + "'" + ',1)">Đi từ điểm này</a></span> | <span id="action"><a onclick="updateEndPoint(' + "'" + item.reference + "'" + ',' + "'" + item.name + "'" + ',1)">Đến điểm này</a></span>'
                                + '</li>';
                $('#list').append(line);
            }
            else {
                var service = new google.maps.places.PlacesService(map);
                var request = {
                    reference: item.reference
                }
                service.getDetails(request, function (place, getDetailStatus) {
                    if (getDetailStatus == google.maps.places.PlacesServiceStatus.OK) {
                        line = '<li>'
                                + '<a onclick="moveToGPlace(' + "'" + place.reference + "'" + ')">' + place.address_components[0].short_name + '</a><br />'
                                + '<span>' + place.formatted_address + '</span>'
                                + '<br/><span id="action"><a onclick="updateStartPoint(' + "'" + item.reference + "'" + ',' + "'" + item.name + "'" + ',1)">Đi từ điểm này</a></span> | <span id="action"><a onclick="updateEndPoint(' + "'" + item.reference + "'" + ',' + "'" + item.name + "'" + ',1)">Đến điểm này</a></span>'
                                + '</li>';
                        $('#list').append(line);
                    }
                });
            }
        }
        showSearchBox();
        moveToGPlace(results[0].reference);
    }
    else {
        hideSearchBox();
        openFancybox(); //show message box
    }
}

//search start point of route
function gStartPointSearch_callback(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
        var line;
        $("#sumResult").html("(" + results.length + ")");  //show sum of search result
        for (var i = 0; i < results.length; i++) {
            var item = results[i];
            if (isGPlace(item.types)) {
                line = '<li>'
                                + '<a onclick="moveToGPlace(' + "'" + item.reference + "'" + ')">' + item.name + '</a><br />'
                                + '<span>' + item.vicinity + '</span>'
                                + '<br/><span id="action"><a onclick="updateStartPoint(' + "'" + item.reference + "'" + ',' + "'" + item.name + "'" + ',1)">Chọn điểm này</a></span>'
                                + '</li>';
                $('#list').append(line);
            }
            else {
                var service = new google.maps.places.PlacesService(map);
                var request = {
                    reference: item.reference
                }
                service.getDetails(request, function (place, getDetailStatus) {
                    if (getDetailStatus == google.maps.places.PlacesServiceStatus.OK) {
                        line = '<li>'
                                + '<a onclick="moveToGPlace(' + "'" + place.reference + "'" + ')">' + place.address_components[0].short_name + '</a><br />'
                                + '<span>' + place.formatted_address + '</span>'
                                + '<br/><span id="action"><a onclick="updateStartPoint(' + "'" + place.reference + "'" + ',' + "'" + place.formatted_address + "'" + ',1)">Chọn điểm này</a></span>'
                                + '</li>';
                        $('#list').append(line);
                    }
                });
            }
        }
        showSearchBox();
        moveToGPlace(results[0].reference);
    }
    else {
        hideSearchBox();
        openFancybox(); //show message box
    }
}

//search end point of route
function gEndPointSearch_callback(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
        var line;
        $("#sumResult").html("(" + results.length + ")");  //show sum of search result
        for (var i = 0; i < results.length; i++) {
            var item = results[i];
            if (isGPlace(item.types)) {
                line = '<li>'
                                + '<a onclick="moveToGPlace(' + "'" + item.reference + "'" + ')">' + item.name + '</a><br />'
                                + '<span>' + item.vicinity + '</span>'
                                + '<br/><span id="action"><a onclick="updateEndPoint(' + "'" + item.reference + "'" + ',' + "'" + item.name + "'" + ',1)">Chọn điểm này</a></span>'
                                + '</li>';
                $('#list').append(line);
            }
            else {
                var service = new google.maps.places.PlacesService(map);
                var request = {
                    reference: item.reference
                }
                service.getDetails(request, function (place, getDetailStatus) {
                    if (getDetailStatus == google.maps.places.PlacesServiceStatus.OK) {
                        line = '<li>'
                                + '<a onclick="moveToGPlace(' + "'" + place.reference + "'" + ')">' + place.address_components[0].short_name + '</a><br />'
                                + '<span>' + place.formatted_address + '</span>'
                                + '<br/><span id="action"><a onclick="updateEndPoint(' + "'" + place.reference + "'" + ',' + "'" + place.formatted_address + "'" + ',1)">Chọn điểm này</a></span>'
                                + '</li>';
                        $('#list').append(line);
                    }
                });
            }
        }
        showSearchBox();
        moveToGPlace(results[0].reference);
    }
    else {
        hideSearchBox();
        openFancybox(); //show message box
    }
}

function isGPlace(type) {
    if (type.indexOf("route") != -1)
        return false;
    if (type.indexOf("political") != -1)
        return false;
    if (type.indexOf("sublocality") != -1)
        return false;
    if (type.indexOf("street_address") != -1)
        return false;
    return true;
}

function moveToGPlace(reference) {
     var service = new google.maps.places.PlacesService(map);
     var request = {
        reference: reference
     }
     service.getDetails(request, function (place, getDetailStatus) {
         if (getDetailStatus == google.maps.places.PlacesServiceStatus.OK) {
             showGPlaceInfo(place);
         }
     });
 }

 function showGPlaceInfo(place) {
     var icon = new google.maps.MarkerImage('images/gplace.png'); 
     if(!pointMarker){
         pointMarker = new google.maps.Marker({
            icon: icon,
            map: map
          });
     }

      // Check to see if an InfoWindow already exists
     if (!infowindow) {
         infowindow = new google.maps.InfoWindow();
     }
     else
         infowindow.close();
     
     // Setting the content of the InfoWindow
     var info = createGPlaceInfo(place);
     infowindow.setContent(info);

     google.maps.event.addListener(pointMarker, 'click', function () {
         infowindow.setContent(createGPlaceInfo(place));
         infowindow.open(map, pointMarker); // Opening the InfoWindow  
     });

     pointMarker.setPosition(place.geometry.location);
     infowindow.open(map, pointMarker);
     map.panTo(place.geometry.location);
 }

 function createGPlaceInfo(place) {
     var info = '<div id="info">'
                    + '<div style="float:left; width:180px; ">'
                        + '<span id="title">' + place.name + '</span><br/>'
                        + '<span id="info">' + place.formatted_address + '</span><br/>';
     
     if (place.international_phone_number != undefined)
         info += '<span id="info">' + place.international_phone_number + '</span><br/>';
     if (place.website != undefined)
         info += '<span id="info"><a target="blank" href="' + place.website + '">' + place.website + '</a></span>';
     
     info += '</div>';
     info += '<div style="float:right">';
     info += '<img id="infoImg" src="images/storeImg/' + 'google-places.png' + '"/>';
     info += '</div>';
     info += '</div>';
     
     return info;
 }